var sexJson={'0':'男','1':'女'};
var userSourceJson = {'1':'运营商',  '2':'运营商营业厅', '3':'渠道商'};
var operatorStatusJson = {'1':'已开通','0':'已冻结'};
var isSuperUserJson = {'1':'是','0':'否'};
//页面全局变量  缓存
var userRoleGlobal={
		globalUserRole:{},
		addRoleIds:[],
		delRoleIds:[]
};
$(document).ready(function() {
	//分页
	 $('#myPagination').myPagination({
		 items_per_page:16,
		 pageList:[16],
		 callback:function(pageNumber,pjq){
			 findUserRolesInfo($('#userObjIndex').val(),pageNumber);
		 }
	 });
	// 初始化表格
	initTable();
	// 新增用户button
	$("#addUser").click(function() {
		openAddWin(this);
	});
	//取消
	$("#cancelBtn").click(function() {
		backendCommon.closeWin("addUserWin");
	});
	//取消
	$("#cancelBackUserRoleBtn").click(function() {
		$('#roleList').datagrid('getPager').pagination({
			'pageNumber' : 1
		});
		$('#roleList').datagrid('load', {
			'pageNumber' : 1,
			rn : Math.random()
		});
		backendCommon.closeWin("allotBackUserRoleWin");
	});
	
	
	//密码移上移出
//	$("#pwdDes").mouseover(function(){
//	    $("#pwdDesInfo").show();
//	}).mouseout(function(){
//	    $("#pwdDesInfo").hide();
//	});
	//地市切换
	$("#cityIdIpt").change(function() {
		$("#countyIdIpt").val('');
		var cityId = $("#cityIdIpt").val();
		if(cityId != ''){
			$.post(mainDomain+'/backend/findCountyVOsByCityId.action',{'cityId':cityId},function(rs){
				if(!rs.state){
					var ops = '<option value="">请选择</option>';
					$.each(rs, function(i, value){
						ops +='<option value="'+value.countyId+'">'+value.countyCname+'</option>';
					});
					$("#countyIdIpt").empty().append(ops);
				}
			});
		}else{
			var ops = '<option value="">请选择</option>';
			$("#countyIdIpt").empty().append(ops);
		}
	});
});

// 初始化table
function initTable() {
	$('#tt')
			.datagrid(
					{
						title:'用户列表信息',
						width : backendCommon.getWidth(0.94),
						loadMsg : "数据装载中....",
						url : mainDomain+'/backend/findBackendVOSPgByDTO.action',
						nowrap : false,
						fitColumns : true,
						striped : true,
						rownumbers : true,
						singleSelect : true,
						pagination : true,
						pageSize : 10,
						queryParams : {
							"rn" : Math.random()
						},
						columns : [ [
								{
									field : 'id',
									title : '用户id',
									width:20,
									align : 'center'
								},
								{
									field : 'realName',
									title : '真实姓名',
									width:30,
									align : 'center'
								},
								{
									field : 'userName',
									title : '登录账号',
									width:20,
									align : 'center'
								},
								{
									field : 'staffNo',
									title : '员工编号',
									width:20,
									align : 'center'
								},
								{
									field : 'mobile',
									title : '手机/电话',
									width:30,
									align : 'center',
									formatter : function(value, rec, index) {
										var str="";
										if(rec.mobile && rec.mobile.length > 0){
											str += rec.mobile;
											if(rec.phone && rec.phone.length > 0){
												str += "/" + rec.phone;
											}
										}else{
											if(rec.phone && rec.phone.length > 0){
												str += rec.phone;
											}
										}
										return str;
									}
								},
								{
									field : 'operatorStatus',
									title : '账号状态',
									width:10,
									align : 'center',
									formatter : function(value, rec, index) {
										var str="";
										if(value == 0){
											//冻结
											str += "<span style='color:red;'>"+operatorStatusJson[value]+"</span>";
										}else{
											str += operatorStatusJson[value];
										}
										return str;
									}
								},
								{
									field : 'isSuperUser',
									title : '是否管理员',
									width:15,
									align : 'center',
									formatter : function(value, rec, index) {
										var str=isSuperUserJson[value];
										return str;
									}
								},
								{
									field : 'opt',
									title : '操作',
									width:30,
									align : 'center',
									formatter : function(value, rec, index) {
										var str = "";
										//开通
										if(rec.operatorStatus == 1){
											str += '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="updateBackOperatorStatus('+ index+',0'+ ');">冻结</a>';
										}else{
											str += '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="updateBackOperatorStatus('+ index+',1'+ ');">开通</a>';
										}
										var operatorId = $("#operatorId").val();
										if(rec.id != operatorId){
											str += '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="deleteBackOperator('+ index + ')">删除</a>';
										}
										str += '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="updateBackOperator('+ index+ ');">修改</a>&nbsp;&nbsp;<a href="javascript:void(0);" onclick="openRoleWin('+ index + ')">角色分配</a>';
										return str;
									}
								} ] ]
					});
}


// 搜索
function doSearch() {
	var userName = $("#userName").val();
	var realName = $("#realName").val();
	var staffNo = $("#staffNo").val();
	var operatorStatus = $("#operatorStatus").val();
	var cityId = $("#cityId").val();
	var company = $("#company").val();
	$('#tt').datagrid('load', {
		'userName':userName,
		'realName':realName,
		'staffNo':staffNo,
		'operatorStatus':operatorStatus,
		'cityId':cityId,
		'company':company,
		rn : Math.random()
	});
}


////翻页
//function onPageSelect(pageStartNumber, jq) {
//	var opts = $("#Pagination").myPagination('options');
//	var pageLimit = opts.items_per_page;
//	var queryParams = {
//		'roleName':$("#roleName").val(),
//		'page' : pageStartNumber,
//		'rows' : pageLimit,
//		'rn' : Math.random()
//	};
//	loadData(queryParams);
//	return false;
//}




// 打开窗口
function openAddWin(obj) {
	var top=$(obj).offset().top; 
	$('#addUserWin').window('move',{'top':top});
	$("#backOperatorId").val('');
	$("#realNameIpt").removeAttr("disabled");
	$("#userNameIpt").removeAttr("disabled");
	$("#operatorStatusIpt").removeAttr("disabled");
	backendCommon.openeWin('addUserWin');
	backendCommon.formReset("addUserForm");
	$("#saveBackUserBtn").unbind('click').click(function() {
		addOrUpdateDimAttribute(true);
	});
}

//打开编辑窗口
function updateBackOperator(index){
	var datas = $('#tt').datagrid('getData').rows;
	var obj = datas[index];
	$("#backOperatorId").val(obj.id);
	$("#realNameIpt").val(obj.realName);
	$("#userNameIpt").val(obj.userName);
	$("#oldPassword").val(obj.password);
	$("#passwordIpt").val(obj.password);
	$("#confirmPasswordIpt").val(obj.password);
	$("#staffNoIpt").val(obj.staffNo);
	$("#mobileIpt").val(obj.mobile);
	$("#operatorStatusIpt").val(obj.operatorStatus);
	$("#realNameIpt").attr("disabled","disabled");
	$("#userNameIpt").attr("disabled","disabled");
	$("#operatorStatusIpt").attr("disabled","disabled");
	backendCommon.openeWin('addUserWin');
	$("#saveBackUserBtn").unbind('click').click(function() {
		addOrUpdateDimAttribute(false);
	});
}

//角色分配页面
function allotBackOperatorRole(index){
	var datas = $('#tt').datagrid('getData').rows;
	var obj = datas[index];
	$("#backOperatorIdRole").val(obj.id);
}




//角色搜索
function doSearchRole() {
	var roleName = $("#roleName").val();
	$('#roleList').datagrid('load', {
		'roleName':roleName,
		rn : Math.random()
	});
}

// 后台新增or更新
function addOrUpdateDimAttribute(isAdd){
	//获取页面参数
	var realName = $.trim($("#realNameIpt").val());
	var userName = $.trim($("#userNameIpt").val());
//	var cityId = $("#cityIdIpt").val();
//	var cityName= $("#cityIdIpt").find('option:selected').text();
//	var countyId = $("#countyIdIpt").val();
//	var countyName= $("#countyIdIpt").find('option:selected').text();
//	var businessHall = $("#businessHallIpt").val();
	var password = $.trim($("#passwordIpt").val());
	var confirmPassword = $.trim($("#confirmPasswordIpt").val());
	var staffNo = $("#staffNoIpt").val();
//	var department = $("#departmentIpt").val();
//	var company = $.trim($("#companyIpt").val());
	var mobile = $("#mobileIpt").val();
	var operatorStatus = $("#operatorStatusIpt").val();
	var id = $("#backOperatorId").val();
//	var merchantId = $("#merchantId").val();
	//判断用户姓名是否为空
	if(realName == ''){
		$.messager.alert('提示',"用户姓名不能为空！",'error');
		return false;
	}
	//判断姓名是否是中文
	if(!backendCommon.regIsChinese(realName)){
		$.messager.alert('提示',"用户姓名必须是中文！",'error');
		return false;
	}
	//长度
	if(realName.length >10){
		$.messager.alert('提示',"用户姓名不能超过10个字符！",'error');
		return false;
	}
	
	if(userName == ''){
		$.messager.alert('提示',"登陆账号不能为空！",'error');
		return false;
	}
//	if(cityId == ''){
//		$.messager.alert('提示',"地市不能为空！",'error');
//		return false;
//	}else{
//		if(countyId == ''){
//			countyName = "";
//		}
//	}
	if(password == ''){
		$.messager.alert('提示',"密码不能为空！",'error');
		return false;
	}
	
	var oldPassword = $("#oldPassword").val();
	if(oldPassword != ""){
		//密码修改后   校验长度
		if(password != oldPassword){
			//长度
			if(password.length >20){
				$.messager.alert('提示',"密码长度不能超过20个字符！",'error');
				return false;
			}
		}
	}else{
		//原密码为空
		//长度
		if(password.length >20){
			$.messager.alert('提示',"密码长度不能超过20个字符！",'error');
			return false;
		}
	}
	if(confirmPassword == ''){
		$.messager.alert('提示',"确认密码不能为空！",'error');
		return false;
	}
	if(password != confirmPassword){
		$.messager.alert('提示',"确认密码必须与原密码一致！",'error');
		return false;
	}
	
//	if(businessHall != ''){
//		//长度
//		if(businessHall.length >50){
//			$.messager.alert('提示',"营业厅不能超过50个字符！",'error');
//			return false;
//		}
//	}
	
	if(staffNo != ''){
		//长度
		if(staffNo.length >10){
			$.messager.alert('提示',"员工编号不能超过10个字符！",'error');
			return false;
		}
	}
	
//	if(department != ''){
//		//长度
//		if(department.length >50){
//			$.messager.alert('提示',"部门不能超过50个字符！",'error');
//			return false;
//		}
//	}
//	
//	if(company == ''){
//		$.messager.alert('提示',"所属公司不能为空！",'error');
//		return false;
//	}
	
	//长度
//	if(company.length >50){
//		$.messager.alert('提示',"公司不能超过50个字符！",'error');
//		return false;
//	}
	if(operatorStatus == ''){
		$.messager.alert('提示',"账号状态不能为空！",'error');
		return false;
	}
	
//	if(mobile != ''){
//		//判断是否手机号符合规范
//		if(!backendCommon.regIsMobile(mobile)){
//			$.messager.alert('提示',"手机号码不符合规范！",'error');
//			return false;
//		}
//	}
	
	//参数
	var parm={
			'id':id,
			'realName':realName,
			'userName':userName,
//			'cityId':cityId,
//			'cityName':cityName,
//			'countyId':countyId,
//			'countyName':countyName,
//			'businessHall':businessHall,
			'password':password,
			'confirmPassword':confirmPassword,
			'staffNo':staffNo,
//			'department':department,
//			'company':company,
			'mobile':mobile,
//			'merchantId':merchantId,
			'operatorStatus':operatorStatus,
			'sex':1
	};
	if(isAdd){
		//新增用户
		$.post(mainDomain+'/backend/addBackendOperator.action',parm,function(result){
			if (result.success && result.state == 1) {
				$.messager.alert('提示', '新增成功！');
				$("#tt").datagrid('reload');
				backendCommon.closeWin('addUserWin');
			}else{
				$.messager.alert('提示', result.message);
				return false;
			}
		});
	}else{
		//编辑用户
		$.post(mainDomain+'/backend/updateBackendOperator.action',parm,function(result){
			if (result.success && result.state == 1) {
				$.messager.alert('提示', '编辑成功！');
				$("#tt").datagrid('reload');
				backendCommon.closeWin('addUserWin');
			}else{
				$.messager.alert('提示', result.message);
				return false;
			}
		});
	}
}

//冻结or开通
function updateBackOperatorStatus(index,operatorStatus){
	var tip;
	var operatorStr;
	if(operatorStatus==0){
		tip="账号一旦冻结，无法登录系统，确认冻结吗？";
		operatorStr = "冻结";
	}else{
		tip="确认开通吗？";
		operatorStr = "开通";
	}
	var objs = $('#tt').datagrid('getData').rows;
	var obj = objs[index];
	var id =obj.id;
	var parm = {
			'id':id,
			'operatorStatus':operatorStatus
	};
	$.messager.confirm('提示',tip,function(r){   
		if (r){   
			$.post(mainDomain+'/backend/updateBackendUserStatusByDTO.action',parm,function(result){
				if(!$.isEmptyObject(result)){ 
					if (result.success) {
						if(id==objs[index].id){
							objs[index].operatorStatus=operatorStatus;
							$('#tt').datagrid('refreshRow',index);
						}else{
							$('#tt').datagrid('reload');
						}
						$.messager.alert('提示',operatorStr+'成功!','info');
					}else{
						$.messager.alert('提示',result.message);
						return false;
					}
				}
			},'json');
		}
	});
}

//删除用户
function deleteBackOperator(index){
	var objs = $('#tt').datagrid('getData').rows;
	var obj = objs[index];
	var id =obj.id;
	var parm ={
			'id':id
	};
	$.messager.confirm('提示','确认删除此用户?',function(r){   
		if (r){   
			$.post(mainDomain+'/backend/deleteBackOperatorByDTO.action',parm,function(result){
				if(!$.isEmptyObject(result)){ 
					if (result.success) {
						if(id==objs[index].id){
							objs.splice(index, 1); 
							$('#tt').datagrid('loadData',{"total":objs.length,"rows":objs});
						}else{
							$('#tt').datagrid('reload');
						}
						$.messager.alert('提示','删除成功!','info');
					}else{
						$.messager.alert('提示',result.message,'info');
						return false;
					}
				}
			},'json');
		}
	});
}



//重置
function clearForm() {
	backendCommon.formReset("searchForm");
	return false;
}

function openRoleWin(index){
	$("#roleName").val('');
	$('#userObjIndex').val(index);
	userRoleGlobal.delRoleIds=[];
	userRoleGlobal.addRoleIds=[];
	findUserRolesInfo(index,1);
	backendCommon.openeWin('allotBackUserRoleWin',390);
	//保存
	$("#saveBackUserRoleBtn").unbind('click').click(function() {
		//保存角色分配
		saveUserRolse();
	});
	$("#cancelRole").unbind('cancelRole').click(function() {
		backendCommon.closeWin("allotBackUserRoleWin");
	});
	
	$("#roleSearchBtn").unbind('click').click(function() {
		 findUserRolesInfo($('#userObjIndex').val(),1);
	});
	
}
function findUserRolesInfo(index,pageNumber){
	var datas = $('#tt').datagrid('getData').rows;
	var obj = datas[index];
	$("#backOperatorIdRole").val(obj.id);
	if(obj.id in userRoleGlobal.globalUserRole){
		getRolsePagList(obj.id,pageNumber);
	}else{
		$.post(mainDomain+'/backend/findUserRole.action',{'backOperatorId':obj.id},function(rs){
			var ids=[];
			if(!$.isEmptyObject(rs)){
				for(var i=0;i<rs.length;i++){
					ids[i]=rs[i].roleId;
				}
			}
			userRoleGlobal.globalUserRole[obj.id] = ids;
			getRolsePagList(obj.id,pageNumber);
		},'json');
	}
}
function getRolsePagList(objId,pageNumber){
	$.post(mainDomain+'/user/findRoleList.action',{"roleName":$("#roleName").val(),"roleStatus":1,'page':pageNumber,'rows':16},function(rs){
		renderRoleTable(rs,objId,pageNumber);
	},'json');
}

function renderRoleTable(rs,objId,pageNumber){
	var rolsIds=userRoleGlobal.globalUserRole[objId];
	var datas=rs.rows;
	var len=8;
	var rows=[];
	var allCheck=true;
	rows.push('<tr><th width="50px;"><input type="checkbox" class="roleCheck checkAll"/></th><th width="170px;">角色名称</th><th width="50px;"><input type="checkbox" class="roleCheck checkAll"/></th><th width="170px;">角色名称</th></tr>');
	for(var i=0;i<len;i++){
		rows.push('<tr>');
		var leftIndex=2*i;
		var rightIndex=leftIndex+1;
		if(leftIndex<datas.length){
			var checkAttr='';
			if(rolsIds.indexOf(datas[leftIndex].id)>-1 || userRoleGlobal.addRoleIds.indexOf(datas[leftIndex].id)>-1 ){
				checkAttr='checked';
			}else{
				allCheck=false;
			}
			rows.push('<td width="50px;"><input type="checkbox" class="roleCheck" value="'+datas[leftIndex].id+'" '+checkAttr+'/></td><td width="170px;">'+datas[leftIndex].roleName+'</td>');
		}else{
			rows.push('<td width="50px;"></td><td width="170px;"></td>');
		}
		if(rightIndex<datas.length){
			var checkAttr2='';
			if(rolsIds.indexOf(datas[rightIndex].id)>-1 || userRoleGlobal.addRoleIds.indexOf(datas[rightIndex].id)>-1 ){
				checkAttr2='checked';
			}else{
				allCheck=false;
			}
			rows.push('<td width="50px;"><input type="checkbox" class="roleCheck" value="'+datas[rightIndex].id+'" '+checkAttr2+'/></td><td width="170px;">'+datas[rightIndex].roleName+'</td>');
		}else{
			rows.push('<td width="50px;"></td><td width="170px;"></th>');
		}
		rows.push('</tr>');
	}
	$('#rolesTable').html(rows.join(''));
	if(allCheck){
		$('.checkAll').attr('checked',true);
	}
	var pagnationOpts=$('#myPagination').myPagination('options');
	pagnationOpts.total=rs.total;
	pagnationOpts.current_page=pageNumber-1;
	$('#myPagination').myPagination('refresh');
	$('.checkAll').click(function(){
		if($(this).attr('checked')){
			$('.roleCheck').attr('checked',true).each(function(){
				if(!$(this).hasClass('checkAll')){
					var id=$(this).val();
					if(rolsIds.indexOf(id)==-1 && userRoleGlobal.addRoleIds.indexOf(id)==-1){
						userRoleGlobal.addRoleIds.push(id);
					}
					userRoleGlobal.delRoleIds.remove(id);
				}
			});
		}else{
			$('.roleCheck').removeAttr('checked').each(function(){
				if(!$(this).hasClass('checkAll')){
					var id=$(this).val();
					if(rolsIds.indexOf(id)>-1 && userRoleGlobal.delRoleIds.indexOf(id)==-1){
						userRoleGlobal.delRoleIds.push(id);
					}
					userRoleGlobal.addRoleIds.remove(id);
				}
			});
		}
	});
	$('.roleCheck').not('.checkAll').click(function(){
		
		var id=$(this).val();
		if($(this).attr('checked')){
			if(rolsIds.indexOf(id)==-1 && userRoleGlobal.addRoleIds.indexOf(id)==-1){
				userRoleGlobal.addRoleIds.push(id);
			}
			userRoleGlobal.delRoleIds.remove(id);
		}else{
			if(rolsIds.indexOf(id)>-1 && userRoleGlobal.delRoleIds.indexOf(id)==-1){
				userRoleGlobal.delRoleIds.push(id);
			}
			userRoleGlobal.addRoleIds.remove(id);
		}
	});
}

function saveUserRolse(){
	var datas = $('#tt').datagrid('getData').rows;
	var obj = datas[$('#userObjIndex').val()];
	if(userRoleGlobal.delRoleIds.length==0 && userRoleGlobal.addRoleIds.length==0){
		backendCommon.closeWin('allotBackUserRoleWin');
		return false;
	}
	
	$.post(mainDomain+'/backend/saveBackUserRoles.action',{'backOperatorId':obj.id,'addRoleIds':userRoleGlobal.addRoleIds.join(','),'delRoleIds':userRoleGlobal.delRoleIds.join(',')},function(rs){
		if(rs.success && rs.state==1){
			for(var i=0;i<userRoleGlobal.delRoleIds.length;i++){
				userRoleGlobal.globalUserRole[obj.id].remove(userRoleGlobal.delRoleIds[i]);
			}
			userRoleGlobal.globalUserRole[obj.id] = userRoleGlobal.globalUserRole[obj.id].concat(userRoleGlobal.addRoleIds);
			$.messager.alert('提示','编辑成功!','info');
			backendCommon.closeWin('allotBackUserRoleWin');
		}else{
			$.messager.alert('提示',rs.message,'info');
			return false;
		}
	},'json');
}



Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};